package com.ruoyi.common.utils.http;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DmsHttpParamUtils {

    /**
     * 分解请求头的参数
     * @param headerData
     * @return
     */
    public static Map<String, String> segmentationHeader(String headerData){
        Map<String, String> res = new HashMap<>();
        //检查headerData是否有换行
        String regex="\n";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(headerData);
        boolean hasEnter = m.find();
        if(hasEnter){
            String[] headerList = headerData.split("\n");
            for (String headerParam:
            headerList) {
                Pattern pattern1 = Pattern.compile(":\\s");
                Matcher m1 = pattern1.matcher(headerParam);
                if (m1.find()){
                    res.put(headerParam.split(": ")[0], headerParam.split(": ")[1]);
                }
            }
        }else if(Pattern.compile(":\\s").matcher(headerData).find()){
            try{
                res.put(headerData.split(": ")[0], headerData.split(": ")[1]);
            }catch (Exception e){
                throw new ArrayIndexOutOfBoundsException("接口信息填写错误");
            }
        }else{

        }
        return res;
    }

    /**
     * 分解body中表单的参数
     * @param bodyData
     * @return
     */
    public static Map<String, String> segmentationBodyForm(String bodyData){
        Map<String, String> res = new HashMap<>();
        String regex="&";
        Pattern pattern = Pattern.compile(regex);
        Matcher m = pattern.matcher(bodyData);
        boolean hasEnter = m.find();
        if(hasEnter){
            String[] bodyList = bodyData.split("&");
            for (String bodyParam:
                    bodyList) {
                Pattern pattern1 = Pattern.compile("=");
                Matcher m1 = pattern1.matcher(bodyParam);
                if (m1.find()){
                    res.put(bodyParam.split("=")[0], bodyParam.split("=")[1]);
                }
            }
        }else if(Pattern.compile("=").matcher(bodyData).find()){
            try{
                res.put(bodyData.split("=")[0], bodyData.split("=")[1]);
            }catch (Exception e){
                throw new ArrayIndexOutOfBoundsException("接口信息填写错误");
            }
        }else{

        }
        return res;
    }
}
